package cn.jiyun.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.jiyun.pojo.Pinlun;
import cn.jiyun.pojoday14.Emp;
import cn.jiyun.utils.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import static org.apache.ibatis.ognl.DynamicSubscript.all;

/**
 * @Author: 小周
 * @Package: cn.jiyun.controller
 * @Project: 2210A-project1
 * @name: MongoDBComtroller
 * @Date: 2023/9/7 21:07
 * @Filename: MongoDBComtroller
 */
@RestController
@RequestMapping("mongoDB")
public class MongoDBComtroller {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("addContext")
    public Result test(@RequestBody Pinlun pinlun, HttpServletRequest request){
        //获取当前登录人
        String token = request.getHeader("token");
        //根据token去redis中查询用户信息
        String s1 = (String) redisTemplate.opsForValue().get(token);
        Emp emp = JSONObject.parseObject(s1, Emp.class);
        String s = IdUtil.fastSimpleUUID();
        pinlun.setId(s);
        pinlun.setEid(emp.getEid());
        pinlun.setEname(emp.getEname());
        pinlun.setJoindate(DateUtil.date());
        pinlun.setPhoto(emp.getPhoto());
        Pinlun pinlun1 = mongoTemplate.save(pinlun);
        return Result.ok().data("pinlun1",pinlun1);
    }


    @GetMapping("findPinlun")
    public Result findPinlun(String pid,Integer cid){
        Query pid1 = Query.query(Criteria.where("pid").is(pid).and("cid").is(cid));
        List<Pinlun> pinlunList = mongoTemplate.find(pid1, Pinlun.class);
        for (Pinlun pinlun : pinlunList) {
            Query pid2 = Query.query(Criteria.where("pid").is(pinlun.getId()).and("cid").is(pinlun.getCid()));
            List<Pinlun> pinlunList1 = mongoTemplate.find(pid2, Pinlun.class);
            pinlun.setList(pinlunList1);
        }
//        Collections.sort(pinlunList, Comparator.comparing(Pinlun::getJoindate,(o1,o2)->o2.compareTo(o1)));
        return Result.ok().data("PinList1",pinlunList);
    }
}
